import { ref, onUnmounted } from 'vue'

export function useHeartbeat(sendHeartbeat, interval = 30000, maxFailures = 3, onFailure) {
  const heartbeatInterval = ref(null)
  const failureCount = ref(0)
  const lastHeartbeat = ref(null)

  // 重置失败计数
  const resetFailureCount = () => {
    failureCount.value = 0
  }

  // 处理心跳失败
  const handleHeartbeatFail = () => {
    failureCount.value += 1
    if (failureCount.value >= maxFailures) {
      stopHeartbeat()
      if (onFailure) onFailure()
    }
  }

  // 开始心跳
  const startHeartbeat = () => {
    // 先停止已有的心跳
    stopHeartbeat()

    // 立即发送一次心跳
    sendHeartbeat()
    lastHeartbeat.value = Date.now()

    // 设置定时发送心跳
    heartbeatInterval.value = setInterval(() => {
      sendHeartbeat()
      lastHeartbeat.value = Date.now()

      // 5秒后检查是否收到响应
      setTimeout(() => {
        // 如果5秒内没有重置失败计数，说明心跳失败
        if (failureCount.value > 0) {
          handleHeartbeatFail()
        }
      }, 5000)
    }, interval)
  }

  // 停止心跳
  const stopHeartbeat = () => {
    if (heartbeatInterval.value) {
      clearInterval(heartbeatInterval.value)
      heartbeatInterval.value = null
    }
    failureCount.value = 0
  }

  // 组件卸载时停止心跳
  onUnmounted(() => {
    stopHeartbeat()
  })

  return {
    startHeartbeat,
    stopHeartbeat,
    resetFailureCount,
    lastHeartbeat,
    failureCount
  }
}
